import React, { useState } from 'react';
import "./index.css"
import { Image, Avatar, Dropdown, message } from 'antd';
import { Outlet, useLocation, Link, useNavigate } from 'react-router-dom'
import router from '../../router'
import { menuList } from '../../config/menu'
import * as Icon from '@ant-design/icons';
import {
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  MailOutlined,
  HomeFilled,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PieChartOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { Button, Layout, Menu, theme } from 'antd';
const { Header, Sider, Content } = Layout;


//动态生成icon组件
const iconElement = (name) => {
  return React.createElement(Icon[name])
}

//处理菜单
const menuData = (menuListData) => {
  return menuListData.map(item => {
    const child = {
      key: item.key,
      icon: iconElement(item.icon),
      label: <Link to={item.path}>{item.name}</Link>
    }
    if (item.children) {
      // child.children = menuData(item.children);
      child.children = item.children.map(childItem => {
        return {
          key: childItem.key,
          icon: iconElement(childItem.icon),
          label: <Link to={childItem.path}>{childItem.name}</Link>
        }
      });
    }

    return child;
  });
}

//menu菜单
const items = [
  {
    path: '/home',
    name: '首页',
    key: 'home',
    icon: <HomeFilled />,
    label: <Link to="/home">首页</Link>
  },
  {
    path: '/user',
    name: '用户管理',
    key: 'user',
    icon: <SettingOutlined />,
    label: '用户管理',
    children: [
      {
        path: 'user/role',
        name: '角色管理',
        key: 'role',
        icon: <AppstoreOutlined />,
        label: <Link to="/user/role">角色管理</Link>,
      }
    ]
  },
];

//Dropdown菜单
const dropDownList = [
  {
    label: '用户中心',
    key: '1',
  },
  {
    label: '退出登录',
    key: '2',
  },
]

const getLevelKeys = items1 => {
  const key = {};
  const func = (items2, level = 1) => {
    items2.forEach(item => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};

const Main = () => {
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();
  const navigate = useNavigate();


  // console.log(router.routes);
  // 生成菜单数据
  // const menuItems = menuData(menuList)

  const levelKeys = getLevelKeys(items);
  const [stateOpenKeys, setStateOpenKeys] = useState(['2', '23']);
  const onOpenChange = openKeys => {
    const currentOpenKey = openKeys.find(key => stateOpenKeys.indexOf(key) === -1);
    // open
    if (currentOpenKey !== undefined) {
      const repeatIndex = openKeys
        .filter(key => key !== currentOpenKey)
        .findIndex(key => levelKeys[key] === levelKeys[currentOpenKey]);
      setStateOpenKeys(
        openKeys
          // remove repeat key
          .filter((_, index) => index !== repeatIndex)
          // remove current level all child
          .filter(key => levelKeys[key] <= levelKeys[currentOpenKey]),
      );
    } else {
      // close
      setStateOpenKeys(openKeys);
    }
  };



  //点击头像下拉框
  const clickMenu = ({ key }) => {
    // console.log(key);
    key === '1' && handleUser();
    key === '2' && handleLogout();
  }

  const handleUser = () => {
    navigate('/user/role');
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    navigate('/login');
    message.info('退出登录!')
  };

  return (
    <div className="main">
      <Layout>
        <Sider theme="light" trigger={null} collapsible collapsed={collapsed}>
          <div className="demo-logo-vertical" />
          <div className='logo-container'>
            <Image
              width={150}
              src={require('../../static/img/tuoren.png')}
            />
          </div>
          <Menu
            mode="inline"
            defaultSelectedKeys={['231']}
            openKeys={stateOpenKeys}
            onOpenChange={onOpenChange}
            items={items}
          />
        </Sider>
        <Layout>
          <Header style={{ padding: 0, background: colorBgContainer, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              style={{
                fontSize: '16px',
                width: 64,
                height: 64,
              }}
            />
            <Dropdown
              menu={{
                items: dropDownList,
                onClick: clickMenu
              }}
              placement="bottomLeft"
              arrow
            >
              <Avatar
                style={{ marginRight: 32 }}
                size={48}
                src={require('../../static/img/avatar.jpg')}
              />
            </Dropdown>
          </Header>
          <Content
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </div>
  );
};
export default Main;